package com.cande.loki.exercise.manythread.threadpooltest;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @author ｗｇｆ
 * @date 2021/7/14 10:43
 * @des
 */
public class TestDemo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService ex = Executors.newFixedThreadPool(3);
        ex.submit(()-> {throw new RuntimeException("submit");});
        ex.execute(()-> {throw new RuntimeException("execute");});

        Thread.sleep(3000);
        System.out.println("==============================================");

        System.out.println(7/2);

//线程池参数
        ExecutorService newFixedThreadPool = Executors.newFixedThreadPool(3);
        //不要用上面这种方法
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(3, 5, 30, TimeUnit.SECONDS, new LinkedBlockingQueue<>(15), Executors.defaultThreadFactory());
        Future<String> result1 = threadPoolExecutor.submit(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "thread1";
        });
        Future<String> result2 = threadPoolExecutor.submit(() -> {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "thread2";
        });
        threadPoolExecutor.shutdown();
        System.out.println(result1.get());
        System.out.println(result2.get());

//excutor的submit三种用法
        ExecutorService executor = Executors.newCachedThreadPool();
        //第一种 callable  //用lambd表达式

        Future<Integer> result = executor.submit(new Callable<Integer>() {
            public Integer call() throws Exception {
                return new Random().nextInt();
            }
        });

        //第二种 runnable
        Future resultrunnable = executor.submit(new Runnable() {
            @Override
            public void run() {
                System.out.println("i`m just runnable");
            }
        });

        //第三种
        Data data = new Data();
        Future<Data> resultData = executor.submit(new Task(data) ,data);

        try {
            System.out.println("result:" + result.get());
            System.out.println("resultrunnable:" + resultrunnable.get());
            System.out.println("resultData:" + resultData.get().getName());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
        executor.shutdown();

    }
}
